package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e){
        log.error("系统错误",e);
        return Result.error("系统错误,请联系管理员！");
    }
    @ExceptionHandler
    public Result handleDuplicateException(DuplicateKeyException e) {
        log.error("出错了",e);
        String reg="Duplicate entry '(.*?)'";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(e.getMessage());
        boolean b = matcher.find();
        String msg = matcher.group(1);
        return Result.error(msg+"已存在");
    }
}
